package command

import (
	"fmt"
	"time"

	agentv1beta1 "gopkg.openfuyao.cn/bkeagent/api/v1beta1"
	bkenode "gopkg.openfuyao.cn/bkecommon/cluster/node"

	"gopkg.openfuyao.cn/cluster-api-provider-bke/utils"
)

type Ping struct {
	BaseCommand
	Nodes bkenode.Nodes
}

func (p *Ping) Validate() error {
	return p.validate()
}

func (p *Ping) New() error {
	if err := p.Validate(); err != nil {
		return err
	}
	commandName := fmt.Sprintf("%s-%d", PingCommandNamePrefix, time.Now().Unix())
	commandSpec := GenerateDefaultCommandSpec()
	commandSpec.Commands = []agentv1beta1.ExecCommand{
		{
			ID: "ping",
			Command: []string{
				"Ping",
			},
			Type:         agentv1beta1.CommandBuiltIn,
			BackoffDelay: 3,
		},
	}

	commandSpec.NodeSelector = getNodeSelector(p.Nodes)
	return p.newCommand(commandName, BKEClusterLabel, commandSpec)
}

// Wait wait for command execution completion displayed
func (p *Ping) Wait() (error, []string, []string) {
	err, complete, successNodes, failedNodes := p.waitCommandComplete()
	// means all command not executed
	if !complete && len(failedNodes) == 0 {
		for _, node := range p.Nodes {
			if utils.ContainsString(successNodes, node.Hostname) {
				continue
			}
			failedNodes = append(failedNodes, node.Hostname)
		}
	}
	return err, successNodes, failedNodes
}
